package com.deyuanyun.pic.pipe.controller;

import com.caixu.beanvalidateutil.imlclass.BeanValidateUtil;
import com.caixu.beanvalidateutil.imlclass.VResult;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.pipe.domain.exceldomain.PipeLineCentreImportDemo;
import com.deyuanyun.pic.pipe.domain.exceldomain.PipeSegmentImportDemo;
import com.deyuanyun.pic.pipe.service.PipeSegmentService;
import com.deyuanyun.pic.support.utils.ExcelUtils;
import com.github.pagehelper.Page;

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管道数据管理
 * 
 * @author scalpel
 * @version 1.0
 * @date 2016年1月27日下午7:44:16
 * Method List:                       // 主要函数及其功能
 *             1.---------------- 
 *History:                           // 历史修改记录
 */
@Controller
@RequestMapping("/pipe/segment")
public class PipeSegmentController extends PipeBaseController{

	@Resource
	private PipeSegmentService segmentService;
	
	@RequestMapping("/search.json")
	@ResponseBody
	public void search(HttpServletRequest request){
		
		HashMap map=RequestUtil.parseRequestParamToHashMap(request);
		
		Page<HashMap<String, Object>> main=segmentService.findPage(map);
		PageJsonBean jsonBean=new PageJsonBean(false);
		jsonBean.setList(main);
		AjaxSupport.sendSuccessText("ok", jsonBean);
		
	}
	
	
	
	@RequestMapping("/import.json")
	@ResponseBody
	public void importData(@RequestParam MultipartFile file,HttpServletResponse response,String id) throws IOException, Exception{
		List<PipeLineCentreImportDemo> data= ReadExcel.readExcle(PipeLineCentreImportDemo.class,file.getInputStream(),4,"13");
		data= MyCollectionUtil.removeLastEmpty(data);
		VResult b= BeanValidateUtil.vali2(data,4+"");
		boolean eq=true;
		for(PipeLineCentreImportDemo d:data){
			if(!id.equals(d.getPipeLineId())&&eq)
			{
				eq=false;
			}
		}
		
		if (b.isRelult() && eq){
			try{
				/**
				 * 分批次导入
				 * 每次导入100条
				 * 
				 */
				List<PipeLineCentreImportDemo> tmp=new ArrayList<PipeLineCentreImportDemo>();
				for(int j=0;j<data.size();j+=100)
				{
					tmp.clear();
					for(int i=0;i<100 && (i+j)<data.size();i++)
					{
						tmp.add(data.get(i+j));
					}
					segmentService.importPoint(tmp);
				}
				AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
				
			}catch(Exception e)
			{
				Map<String,Object> m=new HashMap<String,Object>();
				m.put("id", data.get(0).getPipeLineId());
				segmentService.delGis(m);
				response.setStatus(503);
				String error="抱歉，导入失败"+e.getMessage();
				e.printStackTrace();
				AjaxResponse.sendText(response,"{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\": \""+error+"\"}, \"id\" : \"id\"}");
			}
		}else{
			String[] titleArr= ReadExcel.getTitle(file,"in/pipe_segment_gis_t.xls");
            String m=b.getAllString(titleArr);
            response.setStatus(503);
            AjaxResponse.sendText(response,"{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\": \""+(eq?"":"excel中管道与选择管道不同！")+m+"\"}, \"id\" : \"id\"}");
		}
		
	}
	
	@RequestMapping("/importBase.json")
	@ResponseBody
	public void importBase(@RequestParam MultipartFile file,HttpServletResponse response) throws IOException, Exception{
		List<PipeSegmentImportDemo> data= ReadExcel.readExcle(PipeSegmentImportDemo.class,file.getInputStream(),4,"39");
		data= MyCollectionUtil.removeLastEmpty(data);
		VResult b= BeanValidateUtil.vali2(data,4+"");
		if (b.isRelult()){
			 String result=segmentService.importData(data);
			 if(result == null )
			 {
				 AjaxResponse.sendText(response,StaticParam.UPLOAD_FILE_SUCCESS);
			 }else
			 {
				 response.setStatus(503);
		         AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage(result));
			 }
		}else{
			String[] titleArr= ReadExcel.getTitle(file,"in/pipe_segment_t.xls");
            String m=b.getAllString(titleArr);
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage(m));
		}
	}
	
	@RequestMapping("/del.json")
	@ResponseBody
	public void del(HttpServletRequest request){
		String id=request.getParameter("id");
		if(!StringUtils.isEmpty(id))
		{
			HashMap data=RequestUtil.parseRequestParamToHashMap(request);
			segmentService.delInfo(data);
			Map<String,String> result=new HashMap<String,String>();
			result.put("status", "0");
			AjaxSupport.sendSuccessText("ok", result);
		}else{
			Map<String,String> result=new HashMap<String,String>();
			result.put("status", "1");
			AjaxSupport.sendSuccessText("ok", result);
		}
		
	
	}
	
	@RequestMapping("/checkGis.json")
	@ResponseBody
	public void checkGis(String id){
		int num=segmentService.checkGisNum(id);
		Map<String,String> result=new HashMap<String,String>();
		result.put("status", ""+num);
		AjaxSupport.sendSuccessText("ok", result);
	
	}
	
	@RequestMapping("/gisdel.json")
	@ResponseBody
	public void gisdel(HttpServletRequest request){
		HashMap data=RequestUtil.parseRequestParamToHashMap(request);
		int i=segmentService.delGis(data);
		if(i ==1){
			Map<String,String> result=new HashMap<String,String>();
			result.put("status", "0");
			AjaxSupport.sendSuccessText("ok", result);
		}else{
			Map<String,String> result=new HashMap<String,String>();
			result.put("status", "0");
			AjaxSupport.sendSuccessText("ok", result);
		}
	}
	
	@RequestMapping("/excelExport.json")
	@ResponseBody
	public ModelAndView excelExport(HttpServletResponse response,
			HttpServletRequest request) {
		HashMap data=RequestUtil.parseRequestParamToHashMap(request);
		 InputStream filePath = this.getClass().getResourceAsStream("/template/out/pipe_segment_template.xls");
		List<List<String[]>> result = segmentService.excelExport(data);
		// 将Object中存的List取出
		int[] lineStart = new int[] {1 };
		ExcelUtils.jxlExportExcel(filePath, lineStart, "管道信息", result, response);

		return null;
	}
	
	@RequestMapping("/findGis.json")
	@ResponseBody
	public void findGis(HttpServletRequest request,String id){
		Map<String,Object> info=segmentService.findSegmentById(id);
		List<HashMap<String, Object>> data=segmentService.findGis(id);
		StringBuffer json=new StringBuffer("{\"line\":{\"location\":[");
		for(HashMap<String,Object> v : data){
			json.append("\"").append(v.get("CONVERT_X")).append(";").append(v.get("CONVERT_Y")).append("\",");
		}
		if(data.size() >0)
		{
			json.deleteCharAt(json.length()-1);
		}
		json.append("],").append("\"name\":\"").append(info.get("LINENAME")).append("\"},");
		json.append("\"room\":[{").append("\"lng\":").append(info.get("BEGINCONVERT_X")).append(",\"lat\":");
		json.append(info.get("BEGINCONVERT_Y")).append(",\"name\":\"").append(info.get("BEGINVALVEROMMNAME")).append("\",");
		json.append("\"state\":").append(info.get("BEGINISCGSZ")).append("},{");
		
		json.append("\"lng\":").append(info.get("ENDCONVERT_X")).append(",\"lat\":");
		json.append(info.get("ENDCONVERT_Y")).append(",\"name\":\"").append(info.get("ENDVALVEROMMNAME")).append("\",");
		json.append("\"state\":").append(info.get("ENDISCGSZ")).append("}]}");
		
		Map<String,String> m=new HashMap<String,String>();
		m.put("data", json.toString());
		m.put("type", "0");
		AjaxSupport.sendSuccessText("ok", m);
		
	}
}
